package com.gemme.gemme.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.R;
import com.gemme.gemme.home.Home2Fragment;
import com.gemme.gemme.home.PageAllProductBean;
import com.gemme.gemme.home.ProductListActivity;
import com.gemme.gemme.home.ProductListBean;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.shequ.GuanzhuNewFragment;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.wode.ProductNewActivity;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class BrandListBottomView extends RelativeLayout {
    private Context context;
    private String brandName;
    private OnDataChange onDataChange;

    public BrandListBottomView(Context context) {
        this(context,null);
    }

    public BrandListBottomView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BrandListBottomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView();
    }
    private SwipeRefreshLayout mRefreshLayout;
    private SwipeRecyclerView mRecyclerView;
    LinearLayout ll_middle;
    private void initView() {
        LayoutInflater.from(context).inflate(R.layout.brand_list_bottom,this);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        mRecyclerView = findViewById(R.id.recycler_view);

        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);


        int spanCount = 2; // 3 columns
        int spacing = DpUtil.dip2px(context,12); // 50px
        boolean includeEdge = false;
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));



        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(context);
        mRecyclerView.addFooterView(loadMoreView); // 添加为Footer。
        mRecyclerView.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
       /* mRefreshLayout.setOnRefreshListener(mRefreshListener); // 刷新监听。
        mRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。*/

        mRefreshLayout.setEnabled(false);


        ll_middle = findViewById(R.id.ll_middle);

    }

    public void setBrandName(String brandName) {
        this.brandName = brandName + "";
        if(brandName !=null)
            return;
        getDataS();
    }

    ProductListBean productListBean;
    String oneCategoryId;
    String twoCategoryId;
    String price;
    String remode;
    String hotSale;
    String sortOrder;
    String discount;
    String productEffectId;
    int current = 1;
    int size = 100;
    BrandListAdapter mAdapter;
    private void getDataS() {
        //searchKeywork
        String url = DataManager.BaseUrl + "mall/esProduct/searchRelated?";
       if(!TextUtils.isEmpty(brandName)){
            url = url + "brandName=" + brandName;
        }else if(!TextUtils.isEmpty(oneCategoryId)){
            url = url + "oneCategoryId=" + oneCategoryId;
        }

        if(!TextUtils.isEmpty(twoCategoryId)){
            url = url + "&twoCategoryId=" + twoCategoryId;
        }
        if(!TextUtils.isEmpty(price))
            url = url + "&price=" + price;//1-1000  1-   -1

        //remode = remode ： 推荐
        if(!TextUtils.isEmpty(remode))
            url = url + "&remode=" + remode;
        //hotSale = soldNum-desc ；热销
        if(!TextUtils.isEmpty(hotSale))
            url = url + "&hotSale=" + hotSale;

        //sortOrder = price-desc :价格排序
        if(!TextUtils.isEmpty(sortOrder))
            url = url + "&sortOrder=" + sortOrder;
        //discount = discount :查看折扣
        if(!TextUtils.isEmpty(discount))
            url = url + "&discount=" + discount;

        if(!TextUtils.isEmpty(productEffectId)){
            url = url + "&productEffectId=" + productEffectId;   // 美白 : 1278521450449358849 保湿 : 1278521486050611201
        }
            url = url + "&current=" + current;
            url = url + "&size=" + size;
        HashMap<String, String> headMap = new HashMap<>();
        //todo 去除token
//        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(context));
        DataManager.toServer2(context, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {
                    productListBean = JSON.parseObject(response, ProductListBean.class);
                    if(onDataChange != null  && productListBean != null){
                        onDataChange.onDataChange(productListBean);
                    }

                    List<ProductListBean.DataBean.ProductEsVoListBean> productEsVoList = productListBean.getData().getEsProductInfoList();
                    System.out.println("");
                    if(productEsVoList != null){
//                        mAdapter.notifyDataSetChanged(productEsVoList);

                        mRefreshLayout.setRefreshing(false);

//                        initMiddle();

                        // 第一次加载数据：一定要掉用这个方法。
                        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
//                        mRecyclerView.loadMoreFinish(false, true);
                        //暂时去除加载更多 todo
                        mRecyclerView.loadMoreFinish(false, false);

                        if(mAdapter == null){

                            mAdapter = new BrandListAdapter(productEsVoList);
                            mRecyclerView.setAdapter(mAdapter);
                        }else{
                            mAdapter.setData(productEsVoList);
                            mAdapter.notifyDataSetChanged();
                        }

                    }

                }catch (Exception e){

                }
                System.out.println("");
            }
        });
    }
    public void setType(String remode,String hotSale,String sortOrder,String discount){
        this.remode = remode;
        this.hotSale = hotSale;
        this.sortOrder = sortOrder;
        this.discount = discount;
        getDataS();
    }


    public class BrandListAdapter extends RecyclerView.Adapter<BrandListAdapter.ViewHolder>{
        private  List<ProductListBean.DataBean.ProductEsVoListBean> adapterList;

        public BrandListAdapter(  List<ProductListBean.DataBean.ProductEsVoListBean> adapterList  ){
            this.adapterList = adapterList;
        }
        public void setData(List<ProductListBean.DataBean.ProductEsVoListBean> adapterList) {
            this.adapterList = adapterList;
            notifyDataSetChanged();
        }
        @NonNull
        @Override
        public BrandListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.brand_list_bottom_item, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new BrandListAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull BrandListAdapter.ViewHolder holder, int position) {
            try {
                ProductListBean.DataBean.ProductEsVoListBean bean = adapterList.get(position);

                holder.name.setText(bean.getBrandName());
//                holder.des.setText(bean.getProductName());
                holder.price.setText("¥" +bean.getPrice());
//                holder.price2.setText("¥" +bean.getPrice());
//                holder.price2.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线
                String productImg = bean.getAbbreviationPic();
                if(TextUtils.isEmpty(productImg)){
                    holder.picture.setImageResource(0);
                }
                if( productImg.contains(",")){
                    productImg = productImg.substring(0,productImg.indexOf(","));
                }
                Glide.with(holder.picture.getContext()).load(productImg).into(holder.picture);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //todo 进入产品详情有问题
                        Intent intent = new Intent(context, ProductNewActivity.class);
                        intent.putExtra("id",bean.getProductId() + 0L);
                        intent.putExtra("brandId",bean.getBrandId() + 0L);
                        context.startActivity(intent);
                    }
                });

            }catch (Exception e){

            }
        }

        @Override
        public int getItemCount() {
           return adapterList.size();
        }



        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView price;
            TextView price2;
            ImageView picture;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.name);
                price = itemView.findViewById(R.id.price);
                picture = itemView.findViewById(R.id.picture);
                price2 = findViewById(R.id.price2);
            }
        }
    }


        public void setOnDataChange(OnDataChange onDataChange){

            this.onDataChange = onDataChange;
        }

       public interface OnDataChange{
            void onDataChange(ProductListBean productListBean);
        }


}
